from common.db import models
from apps.product.models import *
from apps.order.models import *


# Create your models here.


class Message(models.Model):
    class MsgType(models.Choices):
        PRE_SALE = "产品预售"
        GOT = "已买入"
        SOLD_OUT = "已卖出"
        WANT_BUY = "求Ta"
        GIFT = "赠送"
        TAKE_OUT = "提仓"
        SYSTEM_MSG = "系统消息"
        # GIFT_OVER = "赠送完成"  # GIFT
        TRANSFER = "转账"
        RECEIVE = "收到转账"

    class Source(models.Choices):
        MATCH = "系统匹配"
        DIRECT = "指定用户卖出"
        NORMAL = "正常"

    from_user_id = models.CharField("用户ID", max_length=64, blank=True, null=True)  # 为空表示系统消息
    title = models.CharField("标题")
    content = models.TextField("内容")
    msg_type = models.CharField("消息类型", choices=MsgType.get_choices())
    market_order_id = models.CharField("挂单ID", blank=True, null=True)  # WANT_BUY/GIFT 关联此字段
    order_id = models.CharField("订单ID", blank=True, null=True)  # GOT/SOLD_OUT/TAKE_OUT 关联此字段
    source = models.CharField("来源", choices=Source.get_choices(), default=Source.NORMAL.name)


    def __str__(self):
        return self.title

    def as_dict(self, keys=None, exclude_keys=None):
        import time
        return {
            "id": self.pk,
            "title": self.title,
            'source': self.source,
            "content": self.content,
            "date": time.strftime('%Y-%m-%d', time.localtime(self.add_timestamp)),
            "transmission_msg": self.make_transmission_msg(),
            "avatar": self.from_user.avatar if self.from_user else '',
            "market_order_id": self.market_order_id,
            "order_id": self.order_id,
        }

    @property
    def from_user(self):
        from apps.user.models import User
        return User.objects.filter(pk=self.from_user_id).first()

    def make_notification_msg(self, to_acceptor=True):
        """生成推送通知消息"""
        data = {}
        data['title'] = self.title
        data['text'] = self.content
        data['logo'] = self.from_user.avatar if self.from_user else ''
        data['logourl'] = self.from_user.avatar if self.from_user else ''
        return data

    def make_transmission_msg(self, to_acceptor=True):
        """生成推送透传消息
        {
            "msg_title": "xxxx",
            "msg_content": "xxxx",
            "msg_type": "WANT_BUY",
            "market_order_id": "1111",
            "order_id": "2222"
        }
        """
        data = {}
        data['msg_id'] = self.id
        data['msg_title'] = self.title
        data['msg_content'] = self.content
        data['msg_type'] = self.msg_type
        data['source'] = self.source
        data['msg_type_map'] = dict(self.__class__.MsgType.get_choices())
        data['market_order_id'] = self.market_order_id if self.market_order_id else ''
        data['order_id'] = self.order_id if self.order_id else ''
        if self.msg_type == Message.MsgType.GIFT.name:
            if to_acceptor:
                data['from_user_nickname'] = self.from_user.nickname if self.from_user else ''
                data['product_name'] = self.market_order.product.name if self.market_order else ''
                data['brand_name'] = self.market_order.product.brand.name if self.market_order else ''
                data[
                    'product_price'] = self.market_order.product.last_trade_price.__str__() if self.market_order else ''
        elif self.msg_type == Message.MsgType.WANT_BUY.name:
            if to_acceptor:
                data['from_user_nickname'] = self.from_user.nickname if self.from_user else ''
                data['product_name'] = self.market_order.product.name if self.market_order else ''
                data['brand_name'] = self.market_order.product.brand.name if self.market_order else ''
                data['product_price'] = self.market_order.offered_price.__str__() if self.market_order else ''
        elif self.msg_type == Message.MsgType.SOLD_OUT.name:
            if to_acceptor:
                data['product_name'] = self.market_order.product.name if self.market_order else ''
                order = Order.objects.filter(id=self.order_id).first()
                if order:
                    data['buyer_pay_amount'] = order.amount.__str__()
                    data['repo_real_pay_amount'] = order.repo_real_pay_amount.__str__()
                    data['procedure_real_pay_amount'] = order.procedure_real_pay_amount.__str__()
                    data['real_amount'] = Decimal(order.amount) - Decimal(order.repo_real_pay_amount) - Decimal(
                        order.procedure_real_pay_amount)

        return data

    @property
    def from_user(self):
        from apps.user.models import User
        return User.objects.filter(pk=self.from_user_id).first()

    @property
    def market_order(self):
        from apps.product.models import MarketOrder
        return MarketOrder.objects.filter(pk=self.market_order_id).first()


class UserUnreadMessage(models.Model):
    user_id = models.CharField("接收用户ID", max_length=64)
    unread_message_ids = JSONField("未读消息ID", default={"WANT_BUY": [], "GOT": []})
    last_message_id = JSONField("最后一条消息ID", default={'WANT_BUY': 'want-buy-msg-id', 'GOT': 'got-msg-id'})

    def have_read(self):
        unread_message_ids = self.unread_message_ids
        for type, va in Message.MsgType.get_choices():
            if type in unread_message_ids:
                un_reads = unread_message_ids[type]
                if un_reads:
                    return True
        return False

    @classmethod
    def unread_count(cls, user_id):
        count = 0
        if user_id:
            unread = UserUnreadMessage.objects.filter(user_id=user_id).first()
            if unread:
                unread_message_ids = unread.unread_message_ids
                for k,v in Message.MsgType.get_choices():
                    if k in unread_message_ids:
                     count += len(unread_message_ids[k])
        return count.__str__()

class UserHistoryMessage(models.Model):
    class Meta:
        ordering = ('-add_timestamp',)

    MsgType = Message.MsgType
    user_id = models.CharField("接收用户ID", max_length=64)
    history_message = models.ForeignKey(Message, verbose_name='历史消息ID', related_name='msg', on_delete=models.CASCADE)
    isread = models.BooleanField(verbose_name="是否已读", default=False)
    msg_type = models.CharField("消息类型", choices=MsgType.get_choices(), blank=True, null=True)

    @property
    def is_effective(self):
        if self.msg_type == Message.MsgType.WANT_BUY.name or self.msg_type == Message.MsgType.GIFT.name:
            if self.history_message.market_order_id:
                market_order = MarketOrder.objects.filter(id=self.history_message.market_order_id).first()
                if market_order:
                    if market_order.status == MarketOrder.Status.ING.name:
                        return True
                    else:
                        return False
                else:
                    return False
        else:
            return False


class PushRecord(models.Model):
    class Provider(models.Choices):
        GETUI = '个推'

    class SendType(models.Choices):
        TRANSMISSION = '透传'
        NOTIFY = '通知'

    class Meta:
        ordering = ('-add_timestamp',)

    user_id = models.CharField("接收用户ID", max_length=64, blank=True, null=True)
    message = models.ForeignKey(Message, verbose_name='消息', blank=True, null=True, on_delete=models.CASCADE)
    content = models.TextField("消息内容", blank=True)
    send_type = models.CharField("发送方式", default=SendType.TRANSMISSION.name, choices=SendType.get_choices())
    provider = models.CharField("推送渠道", choices=Provider.get_choices(), default=Provider.GETUI.name)
    success = models.BooleanField("发送成功", default=True)
    provider_response_status_code = models.IntegerField("响应码", default=200)
    provider_response_data = models.TextField(verbose_name="供应商返回数据", blank=True, null=True)

    def __str__(self):
        return '%s-%s' % (self.user_id, self.content)


class UserTransferHistory(models.Model):
    class MsgType(models.Choices):
        TRANSFER = "转账"
        RECEIVE = "收到转账"

    uid = models.CharField("接收用户id")
    user_id = models.CharField("用户ID", max_length=64)
    address = models.CharField("转账地址", blank=True, null=True)
    nickname = models.CharField("用户昵称")
    msg_type = models.CharField("消息类型", choices=MsgType.get_choices())
    account = models.DecimalField("转账金额")

    def __str__(self):
        return self.uid

    def as_dict(self, keys=None, exclude_keys=None):
        import time
        return {
            "id": self.pk,
            "address": self.address,
            "account": self.account,
            "nickname": self.nickname,
            "msg_type": self.msg_type,
            "date": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.add_timestamp)),
            "avatar": self.from_user.avatar if self.from_user else '',
        }

    @property
    def from_user(self):
        from apps.user.models import User
        return User.objects.filter(pk=self.uid).first()